package com.xxh.auth.service;

import com.xxh.common.constant.AuthConstants;
import com.xxh.dataaccess.entity.User;
import com.xxh.dataaccess.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    private HttpServletRequest request;


    //从DB加载用户
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        //从前端获取到客户端ID
        String clientId = request.getParameter(AuthConstants.JWT_CLIENT_ID_KEY);
//        String clientId="";
        //从Db中判断用户是否存在
        User user = userService.findByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        } else {
            //设置当前请求用户的clientID
            if(clientId==null){
                user.setClientid("client");
            }else {
                user.setClientid(clientId);
            }
            ///获取权限
            List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
            System.out.println("获取权限");
            //从Db中加载用户权限
//            List<SysPermission> permissions = sysPermissionService.getPermissionByUid(user.getId());
//            permissions.forEach(sysPermission -> {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
//                grantedAuthorities.add(grantedAuthority);
//            });
            //这里直接给角色吧
            grantedAuthorities.add(new SimpleGrantedAuthority("user"));
            user.setAuthorities(grantedAuthorities);

            //返回用户的信息,并将用户角色信息存入。
            return user;
        }
    }
}
